package org.twf.aicodehelper.config;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.twf.aicodehelper.entity.ChatMemoryPo;
import org.twf.aicodehelper.mapper.ChatMemoryMapper;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class MySqlChatMemoryStore implements ChatMemoryStore {

    private final ChatMemoryMapper mapper;

    /* 读 */
    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        ChatMemoryPo po = mapper.selectById(memoryId.toString());
        if (po == null || po.getMessages() == null) {
            return new ArrayList<>();
        }
        // LangChain4j 已提供的反序列化工具
        return ChatMessageDeserializer.messagesFromJson(po.getMessages());
    }

    /* 写 */
    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        String json = ChatMessageSerializer.messagesToJson(messages);
        ChatMemoryPo po = new ChatMemoryPo();
        po.setMemoryId(memoryId.toString());
        po.setMessages(json);

        // 存在就更新，不存在就插入
        if (mapper.selectById(po.getMemoryId()) != null) {
            mapper.updateById(po);
        } else {
            mapper.insert(po);
        }
    }

    /* 删 */
    @Override
    public void deleteMessages(Object memoryId) {
        mapper.deleteById(memoryId.toString());
    }
}